# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
import random

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.libs.yuntongxun.sms import CCP
from verifications import constants
import logging

logger = logging.getLogger('django')


class SMSCodeView(APIView):
    def get(self, request, mobile):
        """短信验证码获取"""

        # 判断60s内是否给mobile发送短信
        # 获取redis链接
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 1、随机生成6位数的短信验证码
        # sms_code = '%06d' % random.randint(0, 999999)
        sms_code = 888888
        print('短信验证码： %s' % sms_code)

        # 2、在redis中保存验证码的真实内容
        # 创建redis管道对象
        pl = redis_conn.pipeline()
        # 向管道中添加命令
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存短信放松的标记，设置过期时间60s
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 一次性执行管道中所以命令
        pl.execute()

        # 3、使用云通讯给mobile发送短信验证码
        # expires = constants.SMS_CODE_REDIS_EXPIRES // 60

        # try:
        #     res = CCP().send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        # except Exception:
        #     logger.error('发送短信失败')
        #     return Response({'message': '发送短信异常'}, status=status.HTTP_400_BAD_REQUEST)
        #
        # if res != 0:
        #     return Response({'message': '发送短信失败'}, status=status.HTTP_400_BAD_REQUEST)

        # 发送短信任务消息
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, expires)

        # 4、返回应答，短息发送成功
        return Response({'message': 'OK'})
